﻿using System;
using System.Linq;
using System.Text;
using System.Web;

namespace Noria.Web.Utility
{
    internal class Authenticator
    {
        // Create a logger for use in this class
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private static readonly string token = CreateIdentityToken();
        private static readonly string[] blackList = LoadBlackList();
        private static readonly string[] whiteList = LoadWhiteList();

        private static string[] LoadWhiteList()
        {
            string tmp = NConfig.Root.filters.remove;
            return tmp.Split(',');
        }

        private static string[] LoadBlackList()
        {
            string tmp = NConfig.Root.filters.add;
            return tmp.Split(',');
        }

        private static string CreateIdentityToken()
        {
            string user = NConfig.Root.identity.user;
            string code = NConfig.Root.identity.code;
            var buffer = Encoding.UTF8.GetBytes(user + ":" + code);
            var passcode = "Noria " + Convert.ToBase64String(buffer);

            //log.Info("Token: " + token);
            return passcode;
        }

        public void Authenticate(HttpRequest request)
        {
            var path = request.Url.AbsolutePath;
            if (!blackList.Any(path.EndsWith))
                return;
            if (whiteList.Any(path.EndsWith))
                return;

            // we do not use "Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="
            // because godaddy (IIS) hooks basic authentication and destabilizes the result
            if (request.Headers["NAuth"] != token)
                throw new UnauthorizedException();
        }
    }
}